package mspdt.ubzuuch.mn;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;
import org.taptwo.android.widget.ViewFlow.ViewSwitchListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class UBViewActivity extends Activity{
        
        private Spannable com_name, com_desc, com_address, com_fax, com_phone, com_web, com_email;
        private String workday, saturday, sunday, logo;
        private ArrayList<String> images = new ArrayList<String>();
        private ViewFlow gallery;
        private CircleFlowIndicator indicator;
        private GalleryAdapter gal_adapter;
        private int tv_id = 0;
        private int com_id = 0, gal_pos = 0;
        private TextView tv_name, tv_desc, tv_address, tv_fax, tv_phone, tv_web, tv_email, tv_workday, tv_saturday, tv_sunday;
        private ImageView logo_image;
        private TextView full_screen;
        private ImageLoader imgloader;
        private String lat = "", lan = "";
        private NetworkConnectionClass network;
        
      	@Override
    	public void onBackPressed() {
    	   finish();
    	   overridePendingTransition(R.anim.left_in, R.anim.right_out);
    	}
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.ub_view);
                images.add("");
                initialize();

                getData();
        }
        public void onResume()
        {
                super.onResume();
                focusOnView();
                Bundle bundle = getIntent().getExtras();
                tv_id = bundle.getInt("title");
        		findViewById(R.id.footer_info).setBackgroundResource(R.drawable.footer_clicked);
            	findViewById(R.id.footer_map).setBackgroundColor(Color.TRANSPARENT);
            	findViewById(R.id.footer_street_view).setBackgroundColor(Color.TRANSPARENT);
            	findViewById(R.id.footer_video).setBackgroundColor(Color.TRANSPARENT);
            	findViewById(R.id.footer_contact).setBackgroundColor(Color.TRANSPARENT);
        }
        private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                findViewById(R.id.title_scroll_view).scrollTo(findViewById(tv_id).getLeft()-10, 0);
            }
        });
    }
        public void getData()
        {
                images.clear();
                final ProgressDialog dialog = ProgressDialog.show(UBViewActivity.this, null, 
                        getResources().getString(R.string.dialog_please_wait), true);
        
                        final Handler handler = new Handler() {
                           public void handleMessage(Message msg) {
                                   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
                                   if(msg.what==1)
                                   {
                                       tv_name.setText(com_name);
                                       if(!com_desc.toString().contains("null")){tv_desc.setVisibility(View.VISIBLE);tv_desc.setText(com_desc);}
                                       else tv_desc.setVisibility(View.GONE);
                                       
                                       if(!com_address.toString().contains("null")){tv_address.setVisibility(View.VISIBLE);tv_address.setText(com_address);}
                                       else tv_address.setVisibility(View.GONE);
                                       
                                       if(!com_fax.toString().contains("null")){tv_fax.setVisibility(View.VISIBLE);tv_fax.setText(com_fax);}
                                       else tv_fax.setVisibility(View.GONE);
                                       
                                       if(!com_phone.toString().contains("null")){tv_phone.setVisibility(View.VISIBLE);tv_phone.setText(com_phone);}
                                       else tv_phone.setVisibility(View.GONE);
                                       
                                       if(!com_web.toString().contains("null")){tv_web.setVisibility(View.VISIBLE);tv_web.setText(com_web);}
                                       else tv_web.setVisibility(View.GONE);
                                       
                                       if(!com_email.toString().contains("null")){tv_email.setVisibility(View.VISIBLE);tv_email.setText(com_email);}
                                       else tv_email.setVisibility(View.GONE);

                                       if(!workday.toString().contains("null"))
                                    	   tv_workday.setText(workday);
                                       if(!saturday.toString().contains("null"))
                                    	   tv_saturday.setText(saturday);
                                       if(!sunday.toString().contains("null"))
                                    	   tv_sunday.setText(sunday);
                                       imgloader.DisplayImage(logo, logo_image);
                                       gal_adapter=new GalleryAdapter(UBViewActivity.this, images);
                                       gallery.setAdapter(gal_adapter);
                                   }
                                   else
                                	   Toast.makeText(UBViewActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();

                                   dialog.dismiss();
                              }
                           };
                        Thread checkUpdate = new Thread() {  
                           public void run() {
                                   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
                        	   if(network.isConnectedToServer(getResources().getString(R.string.json_ub_url_selected_com)+com_id, 5000) && network.isNetworkConnected())
                        	   {
                                   final StyleSpan bold = new StyleSpan(android.graphics.Typeface.BOLD); 
                                   JSONfuncObject main_json_data = new JSONfuncObject();
                                   JSONObject json_data = main_json_data.getJSONfromURL(UBViewActivity.this.getResources().getString(R.string.json_ub_url_selected_com)+com_id);
                                   Log.d("TEST", "json="+json_data);
                                   try {
									com_name = new SpannableString(json_data.getString("comname"));
									com_desc = new SpannableString("\n"+json_data.getString("about")+"\n");
	                                com_address = new SpannableString(getResources().getString(R.string.view_screen_address)+" "+json_data.getString("address"));
	                                   com_address.setSpan(bold, 0, com_address.toString().indexOf(":"), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
	                                   com_fax = new SpannableString(getResources().getString(R.string.view_screen_fax)+" "+json_data.getString("fax"));
	                                   com_fax.setSpan(bold, 0, com_fax.toString().indexOf(":"), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
	                                   com_phone = new SpannableString(getResources().getString(R.string.view_screen_phone)+" "+json_data.getString("phone"));
	                                   com_phone.setSpan(bold, 0, com_phone.toString().indexOf(":"), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
	                                   com_web = new SpannableString(getResources().getString(R.string.view_screen_web)+" "+json_data.getString("web"));
	                                   com_web.setSpan(bold, 0, com_web.toString().indexOf(":"), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
	                                   com_email = new SpannableString(getResources().getString(R.string.view_screen_email)+" "+json_data.getString("email"));
	                                   com_email.setSpan(bold, 0, com_email.toString().indexOf(":"), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
	                                   lat = json_data.getString(UBViewActivity.this.getResources().getString(R.string.json_view_lat));
	            					   lan = json_data.getString(UBViewActivity.this.getResources().getString(R.string.json_view_lan));
	                                   workday = json_data.getString("workdaytime");
	                                   saturday = json_data.getString("sadaytime");
	                                   sunday = json_data.getString("sundaytime");
	                                   logo = UBViewActivity.this.getResources().getString(R.string.json_ub_logo_image)+json_data.getString("logo");
	                                   String[] image = json_data.getString("image").split(",");
	                                   for(int i=0;i<image.length;i++)
	                                   {
	                                	   if(image.length>0)
	                                		   images.add(UBViewActivity.this.getResources().getString(R.string.json_ub_url_images)+image[i].replace(" ", "%20"));
	                                   }
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
                                   
                                   handler.sendEmptyMessage(1);
                        	   }
                        	   else
                        		   handler.sendEmptyMessage(0);

                              }
                           };
                        checkUpdate.start();
        }
        public void createTitleComponents()
        {
                //Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
                
                //Үндсэн товчлууруудын үйлдэл
                //Буцах товчлуур
                findViewById(R.id.back).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                finish();
                                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                        }
                });
                //Хадгалсан мэдээ унших товчлуур
                findViewById(R.id.title_history).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        	startActivity(new Intent(UBViewActivity.this, ItemActivityFromDB.class));
                        	overridePendingTransition(R.anim.top_in, R.anim.no_anim);
                        }
                });
                //Хайх товчлуур
                findViewById(R.id.title_search).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        	startActivity(new Intent(UBViewActivity.this, SearchActivity.class));
                        	overridePendingTransition(R.anim.top_in, R.anim.no_anim);
                        }
                });
                //Тухай товчлуур
                findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        	startActivity(new Intent(UBViewActivity.this, InformationActivity.class));
                        	overridePendingTransition(R.anim.top_in, R.anim.no_anim);
                        }
                });
                //Home буюу лого дээр дарах үйлдэл
                findViewById(R.id.home).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        }
                });
                
                
                findViewById(R.id.footer_map).setOnClickListener(new OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				// TODO Auto-generated method stub
        				Intent intent = new Intent(UBViewActivity.this, ViewMapActivity.class);
        				Bundle bundle = new Bundle();
        				bundle.putInt("lat", (int)(Float.parseFloat(lat)*1e6));
        				bundle.putInt("lon", (int)(Float.parseFloat(lan)*1e6));
        				bundle.putString("strval", com_name+"<br>"+com_desc);
                		findViewById(R.id.footer_map).setBackgroundResource(R.drawable.footer_clicked);
                    	findViewById(R.id.footer_info).setBackgroundColor(Color.TRANSPARENT);
                    	findViewById(R.id.footer_street_view).setBackgroundColor(Color.TRANSPARENT);
                    	findViewById(R.id.footer_video).setBackgroundColor(Color.TRANSPARENT);
                    	findViewById(R.id.footer_contact).setBackgroundColor(Color.TRANSPARENT);
        				intent.putExtras(bundle);
        				startActivity(intent);
        				overridePendingTransition(R.anim.bottom_in, R.anim.no_anim);
        			}
        		});
//                findViewById(R.id.footer_video).setOnClickListener(new OnClickListener() {
//        			
//        			@Override
//        			public void onClick(View v) {
//        				// TODO Auto-generated method stub
//        				if(!video.equals("") && !video.equals("null") && video != null)
//        				{
//        					String subbed_string = video.substring(video.indexOf("embed/")+6, video.length());
//        					String video_id = subbed_string.substring(0, subbed_string.indexOf("\""));
//        					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+video_id)); 
//        					intent.putExtra("VIDEO_ID", video_id); 
//        					startActivity(intent);
//        				}
//        				else
//        				{
//        					Toast.makeText(ViewActivity.this, "Видео байхгүй байна", 2000).show();
//        				}
//        				
//        			}
//        		});
        		findViewById(R.id.footer_contact).setOnClickListener(new OnClickListener() {
        			
        			@Override
        			public void onClick(View v) {
        				// TODO Auto-generated method stub

                		findViewById(R.id.footer_contact).setBackgroundResource(R.drawable.footer_clicked);
                    	findViewById(R.id.footer_info).setBackgroundColor(Color.TRANSPARENT);
                    	findViewById(R.id.footer_street_view).setBackgroundColor(Color.TRANSPARENT);
                    	findViewById(R.id.footer_video).setBackgroundColor(Color.TRANSPARENT);
                    	findViewById(R.id.footer_map).setBackgroundColor(Color.TRANSPARENT);
        				Intent intent = new Intent(UBViewActivity.this, ContactUsActivity.class); 
        				Bundle bundle = new Bundle();
        				bundle.putString("contact", "From UB");
        				intent.putExtras(bundle); 
        				startActivity(intent);
        				overridePendingTransition(R.anim.bottom_in, R.anim.no_anim);
        				
        			}
        		});
                
                //Програмын үндсэн менюны үйлдлүүд
                findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(UBViewActivity.this, MainActivity.class); 
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                        }
                });
                findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(UBViewActivity.this, RentActivity.class); 
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                        }
                });
                findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(UBViewActivity.this, NewApartmentActivity.class); 
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                        }
                });
                findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(UBViewActivity.this, UBActivity.class); 
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                        }
                });
                findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
                        
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(UBViewActivity.this, AutomobileActivity.class); 
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                        }
                });
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            setContentView(R.layout.ub_view);
            initialize();
            tv_name.setText(com_name);
            if(!com_desc.toString().contains("null")){tv_desc.setVisibility(View.VISIBLE);tv_desc.setText(com_desc);}
            else tv_desc.setVisibility(View.GONE);
            
            if(!com_address.toString().contains("null")){tv_address.setVisibility(View.VISIBLE);tv_address.setText(com_address);}
            else tv_address.setVisibility(View.GONE);
            
            if(!com_fax.toString().contains("null")){tv_fax.setVisibility(View.VISIBLE);tv_fax.setText(com_fax);}
            else tv_fax.setVisibility(View.GONE);
            
            if(!com_phone.toString().contains("null")){tv_phone.setVisibility(View.VISIBLE);tv_phone.setText(com_phone);}
            else tv_phone.setVisibility(View.GONE);
            
            if(!com_web.toString().contains("null")){tv_web.setVisibility(View.VISIBLE);tv_web.setText(com_web);}
            else tv_web.setVisibility(View.GONE);
            
            if(!com_email.toString().contains("null")){tv_email.setVisibility(View.VISIBLE);tv_email.setText(com_email);}
            else tv_email.setVisibility(View.GONE);

            if(!workday.toString().contains("null"))
         	   tv_workday.setText(workday);
            if(!saturday.toString().contains("null"))
         	   tv_saturday.setText(saturday);
            if(!sunday.toString().contains("null"))
         	   tv_sunday.setText(sunday);
            imgloader.DisplayImage(logo, logo_image);
            gal_adapter=new GalleryAdapter(UBViewActivity.this, images);
            gallery.setAdapter(gal_adapter);
            super.onConfigurationChanged(newConfig);
        }
        public void initialize()
        {
            network=new NetworkConnectionClass(this);
            imgloader = new ImageLoader(this);
            Bundle bundle = getIntent().getExtras();
            tv_id = bundle.getInt("title");
            com_id = bundle.getInt("id");
            gallery = (ViewFlow)findViewById(R.id.view_screen_viewflow_ub);
            indicator = (CircleFlowIndicator) findViewById(R.id.view_screen_indicator_ub);
            gallery.setAdapter(new GalleryAdapter(this, images));
            gallery.setFlowIndicator(indicator);
    		gallery.setOnViewSwitchListener(new ViewSwitchListener() {
    			
    			@Override
    			public void onSwitched(View view, int position) {
    				// TODO Auto-generated method stub
    				gal_pos=position;
    			}
    		});
            tv_name = (TextView)findViewById(R.id.view_screen_tv_name);
            tv_desc = (TextView)findViewById(R.id.view_screen_tv_desc);
            tv_address = (TextView)findViewById(R.id.view_screen_address);
            tv_fax = (TextView)findViewById(R.id.view_screen_fax);
            tv_phone = (TextView)findViewById(R.id.view_screen_phone);
            tv_web = (TextView)findViewById(R.id.view_screen_web);
            tv_email = (TextView)findViewById(R.id.view_screen_email);
            tv_workday = (TextView)findViewById(R.id.view_screen_workday);
            tv_saturday = (TextView)findViewById(R.id.view_screen_saturday);
            tv_sunday = (TextView)findViewById(R.id.view_screen_sunday);
            
            logo_image = (ImageView)findViewById(R.id.view_screen_image);
    		full_screen = (TextView)findViewById(R.id.ub_view_fullscreen);
    		full_screen.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				if(images.size()==0)
    				{
    					Toast.makeText(UBViewActivity.this, "Зураггүй байна", 2000).show();
    				}
    				else
    				{
    					Intent intent = new Intent(UBViewActivity.this, GalleryView.class);
    					Bundle bundle = new Bundle();
    					bundle.putInt("pos", gal_pos);
    					bundle.putStringArrayList("array", images);
    					intent.putExtras(bundle);
    					startActivity(intent);
    					overridePendingTransition(R.anim.right_in, R.anim.no_anim);
    				}
    			}
    		});
            createTitleComponents();
            findViewById(tv_id).setBackgroundResource(R.drawable.text_background);
            focusOnView();
        }
}